package com.sinochem.yunlian.ship.common.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

public class ApiUtil {
	public final static String DEFAULT_CHARSET = "utf-8";
	public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

	/*
	 * 组装请求参数，返回值为key1=value1&key2=value2形式
	 */
	public static String createRequestParam(Map<String, Object> map) {
		StringBuilder param = new StringBuilder();
		for (Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); it
				.hasNext();) {
			Map.Entry<String, Object> e = it.next();
			Object value = e.getValue();
			if (value != null) {
				try {
					value = URLEncoder
							.encode(value.toString(), DEFAULT_CHARSET);
				} catch (UnsupportedEncodingException ex) {
				}
				param.append("&").append(e.getKey()).append("=").append(value);
			}
		}
		return param.toString().substring(1);
	}

	/*
	 * 二行制转字符串
	 */
	private static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

	/*
	 * 签名方法，用于生成签名。
	 * 
	 * @param params 传给服务器的参数
	 * 
	 * @param secret 分配给您的APP_SECRET
	 */
	public static String sign(Map params, String secret) {
		String result = null;
		if (params == null)
			return result;

		// 将参数按key排序
		Set<String> keys = params.keySet();
		String[] ps = new String[keys.size()];
		int i = 0;
		for (String key : keys) {
			Object value = params.get(key);
			if (value != null) {
				ps[i++] = key + value.toString();
			}
		}
		if (i == 0)
			return result;
		String[] ss = new String[i];
		System.arraycopy(ps, 0, ss, 0, i);
		Arrays.sort(ss);

		// 将secret同时放在头尾，拼成字符串
		StringBuilder orgin = new StringBuilder(secret);
		// StringBuilder orgin = new StringBuilder();
		System.out.println(secret);
		for (int j = 0; j < ss.length; j++) {
			System.out.println(ss[j]);
			orgin.append(ss[j]);
		}
		orgin.append(secret);

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		} catch (Exception ex) {
			throw new RuntimeException("sign error !");
		}
		return result;
	}

	/*
	 * 得到返回的内容
	 */
	public static String getResult(String urlStr, String content,
			String reqMethod) {
		URL url = null;
		// HttpsURLConnection connection = null;
		HttpURLConnection connection = null;
		String result = null;

		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			// connection = (HttpsURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod(reqMethod);
			connection.setUseCaches(false);
			connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
			// connection.setHostnameVerifier(new HostnameVerifier() {
			// @Override
			// public boolean verify(String hostname, SSLSession session) {
			// return true;
			// }
			// });
			connection.connect();
			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());
			out.writeBytes(content);
			out.flush();
			out.close();

			// System.out.println(connection.getHeaderFields());
			String encoding = connection.getContentEncoding();
			InputStreamReader is = null;
			BufferedReader reader = null;
			if ("gzip".equals(encoding)) {
				is = new InputStreamReader(new GZIPInputStream(
						connection.getInputStream()), "UTF-8");
				reader = new BufferedReader(is);
			} else {
				is = new InputStreamReader(connection.getInputStream(), "UTF-8");
				reader = new BufferedReader(is);
			}
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				StringBuffer buffer = new StringBuffer();
				String line = "";
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				reader.close();
				result = buffer.toString();
			} else {
				System.out.println("url:" + urlStr + ",ResponseCode:"
						+ connection.getResponseCode() + ",ResponseMessage:"
						+ connection.getResponseMessage());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return result;
	}

	public static String getResult(String urlStr, String content, boolean get) {
		return "";
	}

	public static String getResult(String apiUrl, String appKey,
			String appSecret, String method, Map params, String timestamp,String reqMethod) {
		params.put("app_key", appKey);
		params.put("method", method);
		// params.put("format", format);

		// 时间戳
		params.put("timestamp", timestamp);
		// 生成签名
		// String sign = sign(params, appSecret);
		// 组装协议参数sign
		params.put("sign", appSecret);

		String result = createRequestParam(params);
		return getResult(apiUrl, result, reqMethod);
	}

	static final String APP_KEY = "123";
	static final String APP_SECRET = "123";

//	public static void main(String[] args) throws Exception {
//		Map apiparamsMap = new HashMap();
//		apiparamsMap.put("app_key", APP_KEY);
//		apiparamsMap.put("format", "json");
//
//		apiparamsMap.put("data", "{\"code\":\"0\"}");
//
//
//		apiparamsMap.put("method", "ship.trade.add");
//		apiparamsMap.put("customerId", "wjcp");
//
//		// 时间戳
//		apiparamsMap.put("timestamp", new SimpleDateFormat(
//				"yyyy-MM-dd HH:mm:ss").format(new Date()));
//		// 生成签名
//		String sign = ApiUtil.sign(apiparamsMap, APP_SECRET);
//		System.out.println(sign);
//
//		// 组装协议参数sign
//		apiparamsMap.put("sign", sign);
//
//		String paramStr = ApiUtil.createRequestParam(apiparamsMap);
//
//		String requestUrl = "http://localhost:8771/api/router/trade";
//		requestUrl =	requestUrl + "?" + paramStr;
//
//		System.out.println(requestUrl);
//
//		String str = ApiUtil.getResult("http://localhost:8771/api/router/trade",
//				paramStr, "GET");
//		//System.out.println(str);
//	}

}
